package com.situ.studentmanagement.controller;

import com.situ.studentmanagement.Constants;
import com.situ.studentmanagement.OneDayCheckInfo;
import com.situ.studentmanagement.Utils;
import com.situ.studentmanagement.dao.CheckInfoMapper;
import com.situ.studentmanagement.dao.ClassMapper;
import com.situ.studentmanagement.dao.StudentMapper;
import com.situ.studentmanagement.model.CheckLog;
import com.situ.studentmanagement.model.ClassRoom;
import com.situ.studentmanagement.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by niugao on 7/5/2016.
 */
@Controller //表示这个类是一个Controller，于是当请求路径 / 时，这个Contrller的实例被自动创建
@RequestMapping("/student") //这个controller对应到的路径
public class StudentAcccountController {
    @Autowired
    private CheckInfoMapper checkLogMappler;
    @Autowired
    ClassMapper classMapper;
    @Autowired
    private StudentMapper studentMapper;

    @RequestMapping(value = "/check")
    public String check(HttpSession session,Model model) {
        //获取登录的学生的id
        int student_id = (int) session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID);
        //        List<OneDayCheckInfo> retList=new ArrayList<>();
        //获取考勤信息列表，默认显示当月信息
        String firstDayOfMonth = Utils.getFirstDayOfMonthString(new Date());
        String lastDayOfMonth = Utils.getLastDayOfMonthString(new Date());


        //获取考勤信息列表
        List<CheckLog> checkLogs = checkLogMappler.getCheckLogForOneMonth(
                student_id,  firstDayOfMonth, lastDayOfMonth);
        if(checkLogs.isEmpty()){
            model.addAttribute("check_list",checkLogs);
            model.addAttribute("account_html",Constants.getStudentLoginAcccountHtml(studentMapper,session));
            return "check";
        }

        //由于网页中表格一行显示两次打卡时间，而数据表中一行只有一次打卡时间
        //所以我们需要处理返回的列表checkLogs，取出每一天的两次打卡时间形成一条
        //其实还应该把一天中中间的打卡记录删掉
        //保存一天中第一次打卡时间
//        Date firstCheckTime = checkLogs.get(0).getCheckTime();;
//        //保存一天中最后一次打卡时间，默认改为null
//        Date lastCheckTime = null;
//
//        //使用Calendar才能从Date中获取时间点的天数
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(firstCheckTime);
//        int curDay = calendar.get(Calendar.DAY_OF_YEAR);
//
//        for(int i=1;i<checkLogs.size();i++){
//            Date time = checkLogs.get(i).getCheckTime();
//            //取出time2和time2的天数
//            calendar.setTime(time);
//            int days=calendar.get(Calendar.DAY_OF_YEAR);
//            if(curDay==days){
//                //说明两次打卡在同一天
//                lastCheckTime=time;
//            }else{
//                //一天的完成了，保存下这一天
//                //表格中一条需要显示当天的日期、第一次打卡的时间，最后一次打卡的时间
//                //由于要把这些信息加到网页中，所以直接转成字符串传递更容用在jsp中处理。
//                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
//                String strDay = df.format(firstCheckTime);
//                df=new SimpleDateFormat("hh:mm:ss");
//                String strFirst = df.format(firstCheckTime);
//                String strLast = "";
//                if(lastCheckTime!=null) {
//                    strLast = df.format(lastCheckTime);
//                }
//                retList.add(new OneDayCheckInfo(strDay,strFirst,strLast));
//
//                //开始下一天
//                firstCheckTime=time;
//                lastCheckTime=null;
//                calendar.setTime(time);
//                curDay=calendar.get(Calendar.DAY_OF_YEAR);
//            }
//        }
//
//        //处理最后一天时，肯定遇不到下一天了，所以for循环内的else部分不能被执行
//        //要保存最后一天的日志，必须在这里单独保存
//        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
//        String strDay = df.format(firstCheckTime);
//        df=new SimpleDateFormat("hh:mm:ss");
//        String strFirst = df.format(firstCheckTime);
//        String strLast ="";
//        if(lastCheckTime!=null){
//            df.format(lastCheckTime);
//        }
//        retList.add(new OneDayCheckInfo(strDay,strFirst,strLast));

        //从考勤信息列表产生OneDayCheckInfo列表
        List<OneDayCheckInfo> ret=new ArrayList();
        for(CheckLog cl :checkLogs){
            String curDay = Utils.getDateStringForDay(cl.getCheckInTime());
            String checkInTime = Utils.getDateStringForTime(cl.getCheckInTime());
            String checkOutTime = Utils.getDateStringForTime(cl.getCheckOutTime());
            ret.add(new OneDayCheckInfo(curDay,checkInTime,checkOutTime));
        }

        //通过model向前台传递数据
        model.addAttribute("check_list",ret);
        model.addAttribute("account_html",Constants.getStudentLoginAcccountHtml(studentMapper,session));
        return "check";
    }

    @RequestMapping(value = "/myInfo")
    public String myInfo(Model model,HttpSession session){
        //查数据库，取得当前登录学生的信息
        Student student = studentMapper.getStudentById((int)session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID));
        if(student.getHeadImg()==null){
            student.setHeadImg("/img/default_head_img.png");
        }
        model.addAttribute("student",student);
        model.addAttribute("account_html",Constants.getStudentLoginAcccountHtml(studentMapper,session));
        return "my_info";
    }

    //1 实现提交文件的form
    //2 实现响应文件提交form action的方法
    //3 把文件内容保存到本地文件中，把数据库中student的头像文件名更新
    @RequestMapping(value = "/uploadHeadImg")
    public String uploadHeadImg(Model model,
                                HttpSession session,
                                @RequestParam("head_img") MultipartFile file){
        String errMsg=null;

        //将上传的文件内容保存下来
        if (!file.isEmpty()) {
            try {
                int student_id = (int)session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID);
                byte[] bytes = file.getBytes();
                String path = session.getServletContext().getRealPath("/WEB-INF/img");
                String file_name = "avatar/"+String.valueOf(student_id)+".png";
                BufferedOutputStream stream =new BufferedOutputStream(
                        new FileOutputStream(new File(path+"/"+file_name)));
                stream.write(bytes);
                stream.close();
                //把图片文件名设置到数据库中
                studentMapper.setHeadImgById(student_id,file_name);
            } catch (Exception e) {
                errMsg = e.getLocalizedMessage();
            }
        }

        //查数据库，取得当前登录学生的信息
        Student student = studentMapper.getStudentById((int)session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID));
        if(student.getHeadImg()==null){
            student.setHeadImg("avatar/default_head_img.png");
        }
        model.addAttribute("student",student);
        model.addAttribute("account_html",Constants.getStudentLoginAcccountHtml(studentMapper,session));
        model.addAttribute("errMsg",errMsg);
        return "my_info";
    }
    @RequestMapping(value = "/change")
    public String change(Model model,HttpSession session){

        List<ClassRoom> classArray= classMapper.getAllClassRoom();

        model.addAttribute("classArray",classArray);

        Student student = studentMapper.getStudentById((int)session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID));
        model.addAttribute("student",student);
        model.addAttribute("account_html",Constants.getStudentLoginAcccountHtml(studentMapper,session));
        return "change";
    }

    @RequestMapping(value = "/change_up")
    public String change_up(Model model,HttpSession session,
                            @RequestParam("name") String name,
                            @RequestParam("password") String password,
                            @RequestParam("phone") String phone,
                            @RequestParam("email") String email,
                            @RequestParam("sex") String sex,
                            @RequestParam("address") String address,
                            @RequestParam("class_name") String class_id){
        int sexx;
        if(sex.equals("man")){
            sexx=1;
        }else {
            sexx=0;
        }

        Integer class_Id=Integer.parseInt(class_id);
        int student_id = (int)session.getAttribute(Constants.STUDENT_LOGIN_ATTR_ID);
        studentMapper.change(student_id,name,password,phone,email,sexx,address,class_Id);
        Student student = studentMapper.getStudentById(student_id);
        model.addAttribute("student",student);
        model.addAttribute("account_html",Constants.getStudentLoginAcccountHtml(studentMapper,session));
        return "my_info";
    }
}
